package com.xsz.controller;

import com.xsz.entity.User;
import com.xsz.service.UserService;
import com.xsz.util.MD5Utils;
import com.xsz.util.ResultVOUtil;
import com.xsz.vo.ResultVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;

@RestController
@RequestMapping("user")
@Api(value = "用户控制类")
public class UserController {
    @Resource
    UserService userService;

    @ApiOperation(value = "登录API")
    @PostMapping("/login")
    public ResultVO selectByNamePwd(@RequestBody User user) {
        System.out.println("username***"+user.getName());
        System.out.println("password***"+user.getPwd());
        String password=user.getPwd();
        String username=user.getName();
        password = MD5Utils.encrypt(username, password);
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);
            return ResultVOUtil.success();
        } catch (UnknownAccountException e) {
            return ResultVOUtil.error(500,e.getMessage());
        } catch (IncorrectCredentialsException e) {
            return ResultVOUtil.error(500,e.getMessage());
        } catch (LockedAccountException e) {
            return ResultVOUtil.error(500,e.getMessage());
        } catch (AuthenticationException e) {
            return ResultVOUtil.error(500,"登录失败");
        }
    }

    /**
     *
     * 注册
     * 注意： 数据库保存的密码是 MD5加密以后的密文
     * @param user
     * @return
     */
    @ApiOperation(value = "注册API")
    @PostMapping("/register")
    public ResultVO add(@RequestBody User user) {
        String password = MD5Utils.encrypt(user.getName(), user.getPwd());
        user.setPwd(password);
        return ResultVOUtil.success(userService.add(user));
    }




//    @RequiresPermissions("userInfo:showAll")//权限管理;
//    @GetMapping("/showAll")
//    public ResultVO selectAll() {
//
//        return ResultVOUtil.success(userService.getAll());
//    }


//    @RequiresPermissions("userInfo:showByName")//权限管理;
//    @GetMapping("/showByName/{name}")
//    public ResultVO selectByName(@PathVariable("name") String username) {
//
//        return ResultVOUtil.success(userService.likeName(username));
//    }

}
